package us.mifeng.basicvp.base

import androidx.lifecycle.ViewModel
import io.reactivex.rxjava3.core.Observable
import io.reactivex.rxjava3.disposables.CompositeDisposable
import us.mifeng.basicvp.model.LoginResult
import us.mifeng.basicvp.network.BaseResponse
import us.mifeng.basicvp.network.RxSchedulers
import us.mifeng.basicvp.network.exception.ApiException
import us.mifeng.basicvp.network.exception.ErrorHandler


open class BaseViewModel : ViewModel() {

    protected val compositeDisposable = CompositeDisposable()

    override fun onCleared() {
        super.onCleared()
        compositeDisposable.clear()
    }
    private fun <T> execute(observable: Observable<BaseResponse<T>>): Observable<T & Any> {
        return observable
            .compose(RxSchedulers.io_main())
            .map { response ->
                if (response.code == 200) {
                    response.data ?: throw ApiException(response.code, "数据为空")
                } else {
                    throw ApiException(response.code, response.message)
                }
            }
            .onErrorResumeNext { throwable ->
                Observable.error(ErrorHandler.handleError(throwable))
            }
    }

    protected fun <T : Any> handleResponse(
        observable: Observable<BaseResponse<T>>,
        onSuccess: (T) -> Unit,
        onError: (ApiException) -> Unit = {}
    ) {
        val disposable = execute(observable)
            .subscribe(
                { result -> onSuccess(result) },
                { error ->
                    if (error is ApiException) {
                        onError(error)
                    } else {
                        onError(ApiException(-1, "未知错误"))
                    }
                }
            )
        compositeDisposable.add(disposable)
    }



}